package com.zx.map.controller;

import com.zx.map.dao.model.ShareProfitLog;
import com.zx.map.service.ShareProfitLogService;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.ShareProfitLogModel;
import com.zx.map.utils.SUConstants;
import com.zx.platform.dao.model.Roles;
import com.zx.platform.service.RolesService;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.platform.utils.report.ReportUtil;
import com.zx.utils.WebUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/manage/shareProfitLog")
public class ShareProfitLogController {
	/**
	 * log
	 */
	private static Logger log = Logger
			.getLogger(ShareProfitLogController.class);

	@Autowired
	private ShareProfitLogService shareProfitLogService;


	@Autowired
	private RolesService rolesService;
	/**
	 * 分享收益查询 edit by Jaelyn 2016.12.13
	 * 按当前用户等级和查询的等级  商户信息等查询
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/shareProfitList")
	public String shareProfitList(ShareProfitLog shareProfitLogModel, Model model,
	                              HttpServletRequest request) {

		try {// 初始化信息
			AgentInfoModel curAgentInfoModel= WebUtils.queryCurrentLoginAgentInfo(request);
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();
			// 初始化信息
			initExampleData(shareProfitLogModel,searchAgentInfoModel,curAgentInfoModel);

			Map map = shareProfitLogService.queryShareProfitLog(curAgentInfoModel, searchAgentInfoModel,shareProfitLogModel);

			setResultModelData(shareProfitLogModel,map,model);
			//获取下级代理商级别
			List<Roles> rolesList;
			if(curAgentInfoModel==null) {
				rolesList = rolesService.getDownAgentRolesWithWillAgent(curAgentInfoModel);
			} else {
				rolesList = rolesService.getDownAgentRoles(curAgentInfoModel);
			}
			model.addAttribute("roleList",rolesList);
			return "/jsp/map/shareProfitLog/shareProfitList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 下载分享收益
	 * @param shareProfitLogModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/downLoadProfitList")
	public String downLoadProfitList(ShareProfitLog shareProfitLogModel, Model model,
	                                 HttpServletRequest request, HttpServletResponse response) {
		try {
			AgentInfoModel currentLoginAgentInfo= WebUtils.queryCurrentLoginAgentInfo(request);
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();

			// 初始化信息
			initExampleData(shareProfitLogModel, searchAgentInfoModel,currentLoginAgentInfo);

			shareProfitLogModel.setPageSize(SUConstants.PAGE_NOT_PAGE_COUNT);
			Map map = shareProfitLogService.queryShareProfitLog(currentLoginAgentInfo, searchAgentInfoModel,shareProfitLogModel);
			downLoadProfitList(map,response,"分享收益统计");

			return null;
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}


	}

	private void downLoadProfitList(Map map, HttpServletResponse response,String fileName) throws Exception{
		List<ShareProfitLog> reportList= (List<ShareProfitLog>) map.get("list");

		Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
		formatAttr.put(1, ReportUtil.Date_Time2);
		formatAttr.put(5, ReportUtil.Decimal_Money_chn);
		formatAttr.put(6, ReportUtil.Decimal_Money_chn);

		String[] header = new String[]{"更新时间", "代理商账户", "代理名称", "代理等级", "分享收益金额", "可用余额"};
		String[] feildName=new String[]{"createDate","custSysAccount","agentName","roleName",
				"sprofitBal","sprofitAvlAmt"};
		String sts = ReportUtil.exportReportXLS(header,reportList , null,
				fileName, formatAttr,feildName , response);
		String[] st = sts.split("#");
		ReportUtil.download(response, st[0], st[1]);
	}

	/**
	 * 设置分页返回的数据
	 * @param shareProfitLogModel
	 * @param map
	 * @param model
	 */
	private void setResultModelData(ShareProfitLog shareProfitLogModel, Map map, Model model) {
		int pageSize = shareProfitLogModel.getPageSize();
		int pageNum = shareProfitLogModel.getPageNum();
		List<ShareProfitLogModel> shareProfitList = (List<ShareProfitLogModel>) map.get("list");
		int recordCount = Integer.valueOf(map.get("count").toString());
		// 页面信息
		if (pageSize * pageNum > recordCount + pageSize - 1) {
			pageNum = 1;
		}
		double sprofitBal = (Double) map.get("sprofitBal");
		double sprofitAvlAmt = (Double) map.get("sprofitAvlAmt");
		model.addAttribute("list", shareProfitList);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageCount",
				PmpUtils.getPageCount(recordCount, pageSize));
		model.addAttribute("recordCount", recordCount);
		model.addAttribute("model", shareProfitLogModel);
		model.addAttribute("sprofitBal",sprofitBal);
		model.addAttribute("sprofitAvlAmt",sprofitAvlAmt);
	}


	/**
	 * 初始化查询条件
	 * @param shareProfitLogModel
	 * @param searchAgentInfoModel
	 */
	private void initExampleData(ShareProfitLog shareProfitLogModel, AgentInfoModel searchAgentInfoModel, AgentInfoModel currentLoginAgentInfo) {
		Integer pageNum = shareProfitLogModel.getPageNum();
		Integer pageSize = shareProfitLogModel.getPageSize();
		if (null == pageNum) {
			pageNum = 1;
		}
		if (null == pageSize) {
			pageSize = SUConstants.PAGE_COUNT;
		}
		if(String.valueOf(shareProfitLogModel.getRoleId()).equals(SUConstants.AGENT_LEVEL_WILL)){
			shareProfitLogModel.setIsDirect(1);
		}
		//作为查询条件查询直属商户
		if(shareProfitLogModel.getIsDirect()>0&&currentLoginAgentInfo!=null){
			shareProfitLogModel.setParentAgentId(currentLoginAgentInfo.getAgentId());
		}

		if(StrUtils.isBlank(shareProfitLogModel.getAgentName())){
			shareProfitLogModel.setAgentName(null);
		}
		if(StrUtils.isBlank(shareProfitLogModel.getCustSysAccount())){
			shareProfitLogModel.setCustSysAccount(null);
		}
		shareProfitLogModel.setPageNum(pageNum);
		shareProfitLogModel.setPageSize(pageSize);

		//代理上收缩
		searchAgentInfoModel.setSysAccount(shareProfitLogModel.getCustSysAccount());
		searchAgentInfoModel.setAgentName(shareProfitLogModel.getAgentName());
		searchAgentInfoModel.setAgentLevel(shareProfitLogModel.getRoleId()==null?null:shareProfitLogModel.getRoleId()+"");
		searchAgentInfoModel.setParentAgentId(shareProfitLogModel.getParentAgentId());

	}


}
